package com.example.redisDemo.effective_java;

import java.io.*;
import java.lang.reflect.InvocationTargetException;

public enum MyEnum  {
    INSTANCE;
    public void leaveTheBuilding() {}

    public static void main1(String[] args) throws IOException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        MyEnum myEnum1 = MyEnum.INSTANCE;
        MyEnum myEnum2 = MyEnum.INSTANCE;
        System.out.println(myEnum2==myEnum1);

        // 创建 ByteArrayOutputStream 对象来序列化对象到字节数组
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream out = new ObjectOutputStream(baos);
        // 将对象写入输出流
        out.writeObject(myEnum1);
        // 关闭输出流
        out.close();
        byte[] serializedData = baos.toByteArray();

        // 创建 ByteArrayInputStream 对象来反序列化字节数组为对象
        ByteArrayInputStream bais = new ByteArrayInputStream(serializedData);
        ObjectInputStream in = new ObjectInputStream(bais);
        // 从输入流中读取对象
        MyEnum myEnum3 = (MyEnum) in.readObject();
        // 关闭输入流
        in.close();
        System.out.println(myEnum1==myEnum3);
    }

    public static void main(String[] args) throws Exception {
        MyEnum instance1 = MyEnum.INSTANCE;

        // 获取枚举类型 MyEnum 的 Class 对象
        Class<?> enumClass = MyEnum.class;

        // 使用反射获取 INSTANCE 实例
        Object instance2 = Enum.valueOf((Class<MyEnum>) enumClass, "INSTANCE");

        // 判断是否为 MyEnum 类型的枚举实例
        if (enumClass.isInstance(instance2)) {
            MyEnum myInstance = (MyEnum) instance2;
            System.out.println(myInstance==instance1);
        }
    }
}
